package main;

import org.w3c.dom.ls.LSOutput;

//用泛型的方法自定义封装一个数组
public class genericArrayPack<T> {
    //定义数组变量
    private T[] arr;

    //定义数组中已存在的数据大小
    private int length;

    //有参构造，数组长度由用户用户决定
    public genericArrayPack(int size){
        arr=(T[]) new Object[size];
        length=0;
    }

    //无参构造，默认数组长20
    public genericArrayPack(){
        arr=(T[]) new Object[20];
    }

    //在location处增加数据
    public void Insert(int location,T t){
        if(location<0 || location>length) try {
            throw new Exception("插入位置出错");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (length== arr.length) try {
            throw new Exception("数组下标越界");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (int i = length-1; i >=location ; i--) {
            arr[i+1]=arr[i];
        }
        arr[location]=t;
        length++;
    }

    //在数组尾部插入
    public void InsertLast(T t){
        Insert(length,t);
    }

    //在数组头插入
    public void InsertFirst(T t){
        Insert(0,t);
    }

    //删除location处的数据,并返回数据
    public T delete(int location){
        if(location<0 || location>=length) try {
            throw new Exception("删除位置不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        T data=arr[location];
        for (int i = location+1; i <length ; i++) {
            arr[i-1]=arr[i];
        }
        length--;
        arr[length]=null;
        return data;
    }

    //从数组尾部删除
    public T deleteLast(){
        return delete(length-1);
    }

    //从数组头部删除
    public T deleteFirst(){
        return delete(0);
    }

    //修改数据
    public void update(int location,T t){
        if (location<0 || location>=length){
            try {
                throw new Exception("要修改位置信息不存在");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        arr[location]=t;
    }

    //查询全部数据
    public void selectAll(){
        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("当前数组为：\n");

        if (length==0){
            System.out.println("数组中暂时无数据");
        }else {
            for (int i = 0; i <length ; i++) {
                stringBuffer.append("[");
                stringBuffer.append(arr[i]);
                stringBuffer.append("]\n");
            }
            System.out.println(stringBuffer);
        }
    }

    //根据给出条件查找数组，返回数组下标，没有则返回-1
    public int select(T t){
        for (int i = 0; i <length ; i++) {
            if (arr[i]==t)return i;
        }
        return -1;
    }

    //根据用户给出的下标查找元素
    public T selectLocation(int location){
        if (location<0 || location>=length){
            try {
                throw new Exception("要查询的位置信息不存在");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return arr[location];
    }
}

